﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HyperV;
using System.Management;
using System.Threading;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
using System.Management.Automation;

namespace CopyVMs
{
    class CopyVM
    {

        public static void createRemoteDirectory(String path, String dirname) {
            ManagementScope scope = new ManagementScope(path, null);
            scope.Connect();
            ManagementClass processClass = new ManagementClass(scope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
            ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
            inParams["CommandLine"] = "cmd /c md " + dirname; 
            ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);
        }


        static void Main(string[] args)
        {
            if (args != null && args.Length != 5)
            {
                Console.WriteLine("Usage: .exe hostName exportedVMDirectory parentDiskPath newVMsDirectory newVMName");
            }

            String hostName = args[0];
            String exportedVMDirectory = args[1];
            String parentDiskPath = args[2];
            String newVMsDirectory = args[3];
            String newVMName = args[4];
            String newVMDirectory = newVMsDirectory + "\\" + newVMName + "\\";
            String newVHDPath = newVMDirectory + newVMName + ".vhd";

            Console.WriteLine("Usage: .exe" + hostName +"  " +  exportedVMDirectory +"  " +   parentDiskPath +"  " +   newVMsDirectory +"  " +   newVMName);

            createRemoteDirectory(@"\\" + hostName + @"\root\cimv2", newVMDirectory);
            VMHelper vmHelper = new VMHelper(@"\\"+ hostName+ @"\root\virtualization");
            vmHelper.ImportVirtualSystemEx(exportedVMDirectory, newVMsDirectory, newVMName);
            vmHelper.CreateDifferencingVirtualHardDisk(newVHDPath, parentDiskPath);
            vmHelper.AttachVHDtoVirtualSystem(newVMName, newVHDPath);
            Thread.Sleep(10000);

            //vmHelper.CreateDifferencingVirtualHardDisk(@"d:\1234\1234.vhd", @"D:\VM\VAT-IT-C1N1\VAT-IT-C1N1.vhd");
            //createRemoteDirectory(@"\\bull002.ad.griddynamics.net\root\cimv2", @"d:\1234");
            //VMHelper vmHelper = new VMHelper(@"\\bull002.ad.griddynamics.net\root\virtualization");
        }
    }
}
